package com.gang.blog.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.gang.blog.domain.Category;
import com.gang.blog.domain.User;
import com.gang.blog.domain.UserExpand;
import com.gang.blog.service.CategoryService;
import com.gang.blog.service.UserService;
import com.gang.blog.util.PathUtil;
import com.mysql.fabric.Response;


@Controller
@RequestMapping("/user")
@Transactional
public class UserController {
	
	@Resource
	private UserService userService;
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	@Resource
	private CategoryService categoryService;
	
	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	
	
	@RequestMapping(value="/showUser")
	public String toIndex(HttpServletRequest request,Model model){
		
		//int useId =Integer.getInteger(request.getParameter("id"));
		User user = this.userService.getUserById(1);
//		User user = new User();
//		user.setUserName("fdjlk");
//		user.setUserPassword("132");
//		user.setUserId(1);
//		user.setUserEmial("54456");
//		
		model.addAttribute("user",user);
		return "register" ;
	}
	
	/**
	 * 实现登录操作
	 * @param userName
	 * @param userPassword
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/login")
	public String login(@Param("userName")String userName,@Param("userPassword") String userPassword,HttpServletRequest request,Model model){
		User user = new User();
		System.out.println("userName="+userName);
			user.setUserName(userName);
			user.setUserPassword(userPassword);
			User u = this.userService.checkLogin(user);
			//UserExpand userExpand = this.userService.getUserExpand(u.getUserId());
			request.getSession().setAttribute("user", u);
			
			return "forward:/article/showArticleByPage";
			
				
		
	}
	
	@RequestMapping(value="/logout")
	public String logout(HttpServletRequest request){
		User user = (User) request.getSession().getAttribute("user");
		//System.out.println(user);
		if(user!=null){
			request.getSession().removeAttribute("user");
			return "forward:/article/showArticleByPage";
		}else{
			return "error";
		}
	}
	/**
	 * 实现到登录界面的跳转
	 * @param request
	 * @return login.jsp
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/gotoLogin")
	public String gotoLogin(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		return "login";
	}
	
	/**
	 * 提供注册方法
	 * @param request
	 * @param model
	 * @return 
	 */
	
	@RequestMapping(value="/register")
	public String register(@Param("userName")String userName,@Param("userEmail")String userEmail,@Param("userPassword")String userPassword,HttpServletRequest request,Model model){
		User user = new User();
		if(userName != "" && userEmail != "" && userPassword != ""){
			user.setUserEmail(userEmail);
			user.setUserName(userName);
			user.setUserPassword(userPassword);
			boolean mark = this.userService.addUser(user);
			if(mark){
				return "forward:/article/showArticleByPage";
			}else{
				return "error";
			}
		}else{
			return "error";
		}
	}
	
	/**
	 * 提供跳转到注册页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/gotoRegister")
	public String gotoRegister(HttpServletRequest request,Model model){
		return "register";
	}
	/**
	 * 响应ajax请求，返回数据
	 * @param userName
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/checkUser")
	public Map<String, Object> checkUser(@Param("userName") String userName,Model model){
		Map<String, Object> resultMap = new HashMap<String, Object>();
 		User user = this.userService.checkUserName(userName);
 		//判断user是否为空，当user为空是表示userName可用，user不为空表示userName为已注册
 		if(user!=null){
 			resultMap.put("result", false);
 		}else{
 			resultMap.put("result", true);
 		}
		return resultMap;
	}
	
//	@RequestMapping(value="/uploadUserhead")
//	public String uploadUserhead( @Param("file") MultipartFile file,HttpServletRequest request,Model model ){
//		User user = (User) request.getAttribute("user");
//		//获取本地路径，如果是tomcat的话，在tomcat安装目录的webapp/项目名/imgages/
//		//例如本例"D:\gang\tomcat7.0.68\webapps\blog4\images"
//		String path = request.getSession().getServletContext().getRealPath("images");
//		//获取上传文件的实际名字
//		String fileName = file.getOriginalFilename();
//		//获取文件类型，截取fileName最后一个“.”之后的字符
//		String fileType = fileName.substring(fileName.lastIndexOf("."));
//		//在path目录下新建文件，以当前时间+类型命名文件
//		File targetFile = new File(path,user.getUserId()+fileType);
//		//判断文件是否存在
//		if(!targetFile.exists()){
//			targetFile.mkdirs();
//		}
//		//保存文件
//		try{
//			file.transferTo(targetFile);
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//		String fileUrl = "/images/"+targetFile.getName();
//		return "ok";
//	}
	
	@RequestMapping("/edit")
	public String edit(@Param("file") MultipartFile file,@Param("sex")Integer sex,@Param("introduce") 
		 	String introduce,@Param("description") String description,HttpServletRequest request)
	{
		//获取session中的user
		User user = (User) request.getSession().getAttribute("user");
		String path = request.getSession().getServletContext().getRealPath("images");
		System.out.println(path);
		String address = PathUtil.PathAddress();
//		System.out.println("path="+path);
		System.out.println("address"+address);
		//获取上传文件的实际名字
		String fileName = file.getOriginalFilename();
		//获取文件类型，截取fileName最后一个“.”之后的字符
		String fileType = fileName.substring(fileName.lastIndexOf("."));
		//在path目录下新建文件，以当前时间+类型命名文件
		
		File targetFile = new File(path,user.getUserId()+fileType);
		//判断文件是否存在
		if(!targetFile.exists()){
			targetFile.mkdirs();
		}
		//保存文件
		try{
			file.transferTo(targetFile);
		}catch(Exception e){
			e.printStackTrace();
		}
		String userHeader = address+"images/"+targetFile.getName();
		user.setUserHeader(userHeader);
		int count = this.userService.updateById(user);
		
//		UserExpand userExpand = new UserExpand();
//		userExpand.setUserHeadUrl(userHeadUrl);
//		userExpand.setIntroduce(introduce);
//		userExpand.setDescription(description);
//		userExpand.setSex(sex);
//		userExpand.setUser(user);
		if(count > 0){
			return "ok";
		}else{
			return "error";
		}
	}
	
	@RequestMapping(value="/upload")
	public String upload(){
		return "/personal/editUserInfo";
	}
	
	@RequestMapping(value="/editUserInfo")
	public String editUserInfo(){
		return "/personal/editUserInfo";
	}
}
